package com.example.gcmtest;

import static com.example.gcmtest.CommonUtilities.*;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;
import android.util.Log;

import com.example.gcmtest.MarathonDataBase.MarathonDataBase;
import com.google.android.gcm.GCMBaseIntentService;
import com.google.android.maps.GeoPoint;


//=================================================================
// IntentService GCMから帰ってきたメッセージをハンドリングする処理
//=================================================================
public class GCMIntentService extends GCMBaseIntentService{


	public double latitude=0;
	public double longitude=0;
	public String Send_ID="";
	public boolean gcm_flg;
	private MarathonDataBase marathonDB; // データベースクラス


	StringBuilder sb= new StringBuilder();

	GeoPoint gp_S;
	GeoPoint gp_E;
	GeoPoint gp_P;

	Context cont;

	// publicのコンストラクタ。親コンストラクタにセンダーIDを渡す。
	public GCMIntentService(){
		super(SENDER_ID);
		// データベースクラス取得
		//marathonDB = new MarathonDataBase(this);
		marathonDB = MarathonDataBase.getInstance();
	}


	// 登録インテントを受信した後に呼び出される。GCMから割り当てられる登録IDを取得することができる。
	@Override
	protected void onRegistered(Context context, String registrationId) {
		Log.i(CommonUtilities.TAG_GCM, "Device registered: regId = " + registrationId);
		marathonDB.setText("ID",registrationId);
	}

	// GCMから登録解除された後に呼び出される。
	@Override
	protected void onUnregistered(Context context, String registrationId) {
		Log.i(CommonUtilities.TAG_GCM, "Device unregistered: regId = " + registrationId);
	}

	// サードパーティサーバなどからGCMにメッセージ登録を行うとGCMはメッセージをデバイスに配信する。その時に呼び出される。
	@Override
	protected void onMessage(Context context, Intent intent) {
		String[] aray_msg;
		String str = intent.getStringExtra("message");
		Log.i(CommonUtilities.TAG_GCM, "Received message:" + str);
		aray_msg = str.split(",");

		Log.i(CommonUtilities.TAG_GCM, aray_msg[0]);

        // メッセージ受信
        if(aray_msg[0].equals("1")){
        	generateNotification(context, aray_msg[1]);
        }

        // 登録申請メッセージ
        if(aray_msg[0].equals("2")){
    		// 登録人数取得
    		int RegNo = marathonDB.getInteger("regno", 0);
    		String MyId = marathonDB.getText("ID","NoID");
    		String Name = marathonDB.getText("NAME","NoName");

    		Log.i(CommonUtilities.TAG_GCM, aray_msg[1]);
    		Log.i(CommonUtilities.TAG_GCM, aray_msg[2]);
			RegNo++;
			marathonDB.setInteger("regno", RegNo);
			marathonDB.setText("ID"+ RegNo, aray_msg[1]);
			marathonDB.setText("NAME"+ RegNo,aray_msg[2]);
			String[] ids = {aray_msg[1]};
			SendAsyncTask task = new SendAsyncTask(ids,"3,"+ MyId + "," + Name + ",");
			task.execute();
			generateNotificationReg(context,aray_msg[1]);
        }

        // 登録完了通知表示処理
        if(aray_msg[0].equals("3")){
    		// 登録人数取得
    		int RegNo = marathonDB.getInteger("regno", 0);
			RegNo++;
			marathonDB.setInteger("regno", RegNo);
			marathonDB.setText("ID"+ RegNo, aray_msg[1]);
			marathonDB.setText("NAME"+ RegNo,aray_msg[2]);
	    	generateNotificationOK(context, aray_msg[1]);
        }

        // GPS取得要求受信処理
        if(aray_msg[0].equals("4")){
    		Send_ID = aray_msg[1];

    		latitude = Double.parseDouble(marathonDB.getText("LATITUDE","0.0"));
    		longitude = Double.parseDouble(marathonDB.getText("LONGITUDE","0.0"));

       		Log.i(CommonUtilities.TAG_GCM,"Latitude:"+ latitude + " Longitude:"+longitude);

       		if(latitude!=0.0 && longitude!=0.0){
				String MyId = marathonDB.getText("ID","NoID");
				String[] ids = {Send_ID};
				SendAsyncTask task = new SendAsyncTask(ids,"5,"+ MyId + "," + latitude + "," + longitude + ",");
				task.execute();
       		}
        }

        // GPS取得完了処理
        if(aray_msg[0].equals("5")){
        	int RegNo =marathonDB.friendIdSearch(aray_msg[1]);
        	Log.i(CommonUtilities.TAG_GCM,"======================================>[" + RegNo + "]緯度："+aray_msg[2]+" 経度："+aray_msg[3]);
        	// 暫定処理、複数同時にGPS情報が飛んできた場合一つしか変更できないためCHANGE_NOからCHANGE_FLG+RegNoに変更する。
        	if(0 != RegNo)
        	{
            	marathonDB.setBoolean("GPS_FLG",true);
	        	marathonDB.setInteger("CHANGE_NO", RegNo);
	    		marathonDB.setText("RUN_LATI"+RegNo, aray_msg[2]);
	    		marathonDB.setText("RUN_LONGI"+RegNo,aray_msg[3]);
        	}
        }
	}

	//==================================================================================
	// 画面上部通知処理
	//==================================================================================

	/**
     * Issues a notification to inform the user that server has sent a message.
     */
    @SuppressLint("NewApi")
	private static void generateNotification(Context context, String message) {
    	Intent notificationIntent = new Intent(context, MainActivity.class);
    	PendingIntent pendingIntent =
    			PendingIntent.getActivity(context, 0, notificationIntent, 0);

    	//Notification.Builder builder = new Notification.Builder(context);
    	Builder builder = new NotificationCompat.Builder(context);

    	builder.setTicker("通知テスト受信");
    	builder.setContentTitle("GCM通知テスト");
       	builder.setContentText(message);
       	builder.setContentInfo("info");
       	builder.setWhen(System.currentTimeMillis());
       	builder.setContentIntent(pendingIntent);
       	builder.setSmallIcon(android.R.drawable.ic_menu_info_details);
       	Notification notification = builder.build();

        NotificationManager notificationManager = (NotificationManager)
                context.getSystemService(Context.NOTIFICATION_SERVICE);
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(1, notification);
        Log.i(CommonUtilities.TAG_GCM, "generateNotification:" + message);
    }


    /**
     * Issues a notification to inform the user that server has sent a message.
     */
    @SuppressLint("NewApi")
	private static void generateNotificationReg(Context context, String message) {
    	Intent notificationIntent = new Intent(context, MainActivity.class);
    	PendingIntent pendingIntent =
    			PendingIntent.getActivity(context, 0, notificationIntent, 0);

    	//Notification.Builder builder = new Notification.Builder(context);
    	Builder builder = new NotificationCompat.Builder(context);

    	builder.setTicker("フレンド登録申請");
    	builder.setContentTitle("マラソン応援アプリ：フレンド登録申請");
       	builder.setContentText(message);
       	builder.setContentInfo("info");
       	builder.setWhen(System.currentTimeMillis());
       	builder.setContentIntent(pendingIntent);
       	builder.setSmallIcon(android.R.drawable.ic_menu_info_details);
       	Notification notification = builder.build();

        NotificationManager notificationManager = (NotificationManager)
                context.getSystemService(Context.NOTIFICATION_SERVICE);
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(1, notification);
    }

    /**
     * Issues a notification to inform the user that server has sent a message.
     */
    @SuppressLint("NewApi")
	private static void generateNotificationOK(Context context, String message) {
    	Intent notificationIntent = new Intent(context, MainActivity.class);
    	PendingIntent pendingIntent =
    			PendingIntent.getActivity(context, 0, notificationIntent, 0);

    	//Notification.Builder builder = new Notification.Builder(context);
    	Builder builder = new NotificationCompat.Builder(context);

    	builder.setTicker("フレンド登録完了");
    	builder.setContentTitle("マラソン応援アプリ：フレンド登録完了");
       	builder.setContentText(message);
       	builder.setContentInfo("info");
       	builder.setWhen(System.currentTimeMillis());
       	builder.setContentIntent(pendingIntent);
       	builder.setSmallIcon(android.R.drawable.ic_menu_info_details);
       	Notification notification = builder.build();

        NotificationManager notificationManager = (NotificationManager)
                context.getSystemService(Context.NOTIFICATION_SERVICE);
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(1, notification);
    }

    public class SendAsyncTask extends AsyncTask<String, String, Long> {
		private String[] mRegIds;
		private String mMsg;

	    public SendAsyncTask(String[] regId , String msg) {
	        this.mRegIds = regId;
	        this.mMsg = msg;
	    }

	    /**
	     * バックグランドで行う処理
	     */
	    @Override
	    protected Long doInBackground(String... params) {
	    	//ServerUtilities.sendMessage(mRegId,mMsg);
	        GCMServer.SendMsg(mRegIds,mMsg);
	        return null;
	    }
	}

	@Override
	protected void onError(Context arg0, String arg1) {
		// TODO 自動生成されたメソッド・スタブ

	}

}
